package net.cn_su.sharpeyes.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import net.cn_su.sharpeyes.R;
import net.cn_su.sharpeyes.adapter.OrgAdapter;
import net.cn_su.sharpeyes.adapter.OrgApplyAdapter;
import net.cn_su.sharpeyes.application.SuApplication;
import net.cn_su.sharpeyes.baseadapter.AdapterCallback;
import net.cn_su.sharpeyes.beans.Organization;
import net.cn_su.sharpeyes.pref.ServerInfo_;
import net.cn_su.sharpeyes.utils.UIUtil;
import net.cn_su.sharpeyes.utils.http.HttpClient;
import net.cn_su.sharpeyes.utils.http.HttpUrl;
import net.cn_su.sharpeyes.utils.http.JacksonMapper;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.Fullscreen;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.codehaus.jackson.type.TypeReference;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by Overlord on 2016/08/16.
 * Singularity Universe
 */
@Fullscreen
@EActivity(R.layout.activity_pinnedsection_listview)
public class OrgChooseActivity extends Activity implements AdapterCallback {

    @ViewById
    protected ListView lv_have;
    @ViewById
    protected ListView lv_apply;
    @ViewById
    protected TextView tv_count, tv_empty, tv_update;


    protected OrgAdapter adapter;
    protected OrgApplyAdapter mApplyAdapter;


    @ViewById
    ProgressBar progressBar;

    @Pref
    protected ServerInfo_ serverInfo;

    //判断是否是登录注册过来的
    @Extra
    protected boolean flag;

    @App
    protected SuApplication suApplication;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @AfterViews
    protected void initData() {

        lv_have.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                //查看摄像头
                Organization organization = (Organization) parent.getItemAtPosition(position);
                goBack(organization);


            }
        });

        lv_apply.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Organization organization = (Organization) parent.getItemAtPosition(position);

                switch (organization.getStatus()) {
                    case -1:
                        applyServer(organization.getId());

                        break;
                    case 0:

                        break;
                    case 1:

                        break;
                    case 2:
                        applyServer(organization.getId());
                        break;
                }


            }
        });


        getApplyList();


    }

    private void getApplyList() {

        progressBar.setVisibility(View.VISIBLE);
        RequestParams params = new RequestParams();
        params.add("user_id", serverInfo.userId().get().toString());

        HttpClient.get(HttpUrl.GET_ORG_APPLY, params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                if (progressBar != null) {
                    progressBar.setVisibility(View.GONE);
                    lv_have.setVisibility(View.GONE);
                    tv_count.setText("共0条");
                    tv_empty.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                if (progressBar != null) {
                    progressBar.setVisibility(View.GONE);
                }

             //   Logger.v("result==" + responseString);
                List<Organization> organizationList = JacksonMapper.parseToList(responseString, new TypeReference<List<Organization>>() {
                });
                if (organizationList == null || organizationList.size() == 0) {
                    tv_empty.setVisibility(View.VISIBLE);
                    lv_have.setVisibility(View.GONE);
                    tv_count.setText("共0个");
                    return;
                }

                //去申请列表
                List<Organization> mAllList = getAllOrganizations(organizationList);

             //   Logger.v("size==" + mAllList.size());
                if (adapter == null) {
                    adapter = new OrgAdapter(OrgChooseActivity.this, mAllList, R.layout.item_list_township, OrgChooseActivity.this);
                    lv_apply.setAdapter(adapter);
                } else {
                    adapter.removeAll();
                    adapter.addAll(mAllList);
                }


                //已申请通过的列表
                List<Organization> mApplyList = getApplyOrganizations(organizationList);

                if (mApplyList.size() == 0) {
                    lv_have.setVisibility(View.GONE);
                    tv_count.setText("共0条");
                    tv_empty.setVisibility(View.VISIBLE);

                    lv_apply.requestFocus();
                } else {

                    lv_have.setVisibility(View.VISIBLE);
                    tv_count.setText("共" + mApplyList.size() + "个");
                    tv_empty.setVisibility(View.GONE);

                    if (mApplyAdapter == null) {

                        mApplyAdapter = new OrgApplyAdapter(OrgChooseActivity.this, mApplyList, R.layout.item_list_apply, OrgChooseActivity.this);

                        lv_have.setAdapter(mApplyAdapter);
                    } else {
                        mApplyAdapter.removeAll();
                        mApplyAdapter.addAll(mApplyList);

                    }
                    lv_have.requestFocus();
                }

            }

        });


    }

    /**
     * 得到全部组织列表
     *
     * @param orgs
     * @return
     */
    public List<Organization> getAllOrganizations(List<Organization> orgs) {

        List<Organization> organizations = new ArrayList<>();
        //只包含全部child
        List<Organization> organizationChild = new ArrayList<>();
        // 将镇进行一次处理, 作为村的点来处理
        List<Organization> children = null;
        for (Organization org : orgs) {


            if (org.getChildren() != null && org.getChildren().size() > 0) {
                children = new ArrayList<>();
                children.addAll(org.getChildren());

                organizations.add(new Organization(org.getId(), 0, org.getName(), children.size()));
                organizations.addAll(children);
                organizationChild.addAll(children);
            }


        }

        suApplication.setOrganizations(organizationChild);
        return organizations;
    }

    /**
     * 得到申请通过的列表
     *
     * @param orgs
     * @return
     */
    public List<Organization> getApplyOrganizations(List<Organization> orgs) {
        List<Organization> organizations = new ArrayList<>();
        // 将镇进行一次处理, 作为村的点来处理
        List<Organization> children = null;
        for (Organization org : orgs) {


            if (org.getChildren() != null && org.getChildren().size() > 0) {
                children = new ArrayList<>();
                for (Organization val : org.getChildren()) {
                    if (val.getStatus() == 1) {
                        children.add(val);
                    }
                }
                organizations.addAll(children);
            }
        }

        return organizations;
    }


    @Click(R.id.btn_back)
    protected void back() {
        if (flag) {
            //退出登录
            AlertDialog.Builder dialog = new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("是否立即退出登录")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            LoginActivity_.intent(OrgChooseActivity.this).start();
                            finish();
                            serverInfo.isLogin().put(false);

                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            dialog.create().show();

        } else {
            finish();
        }

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

        if (flag) {
            //退出登录
            AlertDialog.Builder dialog = new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("是否立即退出登录")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            LoginActivity_.intent(OrgChooseActivity.this).start();
                            finish();
                            serverInfo.isLogin().put(false);

                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            dialog.create().show();

        } else {
            finish();
        }
    }

    @Click(R.id.tv_update)
    protected void updateClick() {
        getApplyList();
    }

    private void goBack(Organization org) {

        if (flag) {
            //
            LiveActivity_.intent(this).extra("orgId", org != null ? org.getId() : -1).start();
            finish();
        } else {
            Intent intent = new Intent();
            intent.putExtra("orgId", org != null ? org.getId() : -1);
            OrgChooseActivity.this.setResult(1, intent);
            OrgChooseActivity.this.finish();
        }


    }


    @Override
    public void adapterstartActivity(Class<?> className, Bundle options) {


    }

    @Override
    public void adapterstartActivityForResult(Class<?> className, Bundle options, int requestcode) {

    }

    @Override
    public void adapterInfotoActiity(Object data, int what) {
        Organization organization = (Organization) data;
        switch (what) {

            //查看摄像头
            case 1:
                goBack(organization);
                break;
            //申请
            case 2:
                applyServer(organization.getId());

                break;
        }


    }

    /**
     * 申请
     *
     * @param orgId
     */
    private void applyServer(int orgId) {
        if (progressBar != null) {
            progressBar.setVisibility(View.VISIBLE);
        }

        RequestParams params = new RequestParams();
        params.add("user_id", serverInfo.userId().get().toString());
        params.add("org_id", orgId + "");

        HttpClient.post(this, HttpUrl.GENERAL_PUBLICS, params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                if (progressBar != null) {
                    progressBar.setVisibility(View.GONE);
                }
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {

                UIUtil.showToast(OrgChooseActivity.this, "申请成功，请等待审核");
                getApplyList();
            }
        });
    }
}
